//
//  MarketScene.cpp
//  SpaceTrader
//
//  Created by Brandon Chastain on 10/26/12.
//  Copyright (c) 2012 The Hex Pistols. All rights reserved.
//
//#include "GuiButton.h"
#include "MarketScene.h"
#include "GuiButton.h"
#include <sstream>

MarketScene::MarketScene(Market *market) : market(market), isTrader(false), buttons(std::vector<ShopButton*>()), prices(std::vector<int>()),
                                            lastPlanet(NULL)
{
	for (int i = 0; i < 9; i++) {
		buttons.push_back(new ShopButton());
	}
}

MarketScene::MarketScene(Market *market, bool isTrader) : market(market), isTrader(isTrader), buttons(std::vector<ShopButton*>()),
                                prices(std::vector<int>()), lastPlanet(NULL)
{
	for (int i = 0; i < 9; i++) {
		buttons.push_back(new ShopButton());
	}
}

MarketScene::MarketScene(const MarketScene &M) : market(M.market), isTrader(M.isTrader), buttons(std::vector<ShopButton*>(M.buttons.size())),
                                                    prices(M.prices), lastPlanet(M.lastPlanet)
{
    for (int i = 0; i < 9; i++){
        differences[i] = M.differences[i];
    }
}

MarketScene::~MarketScene(){
    
}

MarketScene& MarketScene::operator=(const MarketScene &M){
    if (&M != this){
        delete lastPlanet;
        for (unsigned int i = 0; i < buttons.size(); i++){
            delete buttons[i];
        }
        
        buttons = std::vector<ShopButton*>(M.buttons.size());
        for (unsigned int i = 0; i < buttons.size(); i++){
            buttons[i] = M.buttons[i];
        }
        market = M.market;
        isTrader = M.isTrader;
        prices = M.prices;
        for (int i = 0; i < 9; i++){
            differences[i] = M.differences[i];
        }
    }
    return *this;
}

/*
 * TODO: rework the updating of button text and state
 * draws the market scene and handles the Market's logic
 * and user input for buying and selling
 */

state_t MarketScene::draw(SDL_Surface *screen, Planet *planet, Player *player, bool trader){
	this->isTrader = trader; //used to determine if we are coming from TravelScene or PlanetScene
    GuiButton backButton(0, 425, "", "Back");
    GuiButton buyButton(375,415, "SmallGuiButton", "Buy");
    GuiButton sellButton(500, 415, "SmallGuiButton", "Sell");
    
    
    unsigned int lastPicked = 0;
	//int quantities[] = { 40, 7, 2, 1, 0, 0, 3, 8, 1 };
	std::vector<std::string> itemList = market->getItemList();
	int* shopQuantities = planet->getInventory();
	if (!trader) {
		if (planet != lastPlanet) {
			prices.clear();
			for (int i = 0; i < 10; i++) {
				TradeGood *t = market->getTradeGood(itemList[i]);
				if (t->getMinProduce() <= planet->getTechLevel()) {
					prices.push_back((t->getBasePrice()+ t->getIncreasePerLevel()*planet->getTechLevel() + ( (rand()%1) ? -1 :1 ) * rand()%t->getVariance())
									 * ((planet->getWorldEvent() == t->getEvent()) ? 2 : 1)
									 / ((planet->getResources() == t->getCheap()) ? 2 : 1 )
									 * ((planet->getResources() == t->getExpensive()) ? 2 : 1));
					differences[i] = prices[i]- t->getBasePrice()+ t->getIncreasePerLevel()*planet->getTechLevel();
				} else {
					prices.push_back(0);
					differences[i] = 0;
				}
			}
		}
	} else {
		prices.clear();
		for (int i = 0; i < 10; i++) {
			int tech = rand()%TECHCOUNT;
			TradeGood *t = market->getTradeGood(itemList[i]);
			prices.push_back(t->getBasePrice()+ t->getIncreasePerLevel()*tech
				+ ( (rand()%1) ? -1 :1 ) * rand()%t->getVariance());
			differences[i] = prices[i] - t->getBasePrice()+ t->getIncreasePerLevel()*tech;
		}
	}

	
	
	lastPlanet = planet;
	/*std::cout << " " << std::endl;
	 for (int i=0; i < itemList.size(); i++) {
	 std::cout << itemList[i] << std::endl;
	 std::cout << market->getTradeGood(itemList[i])->getBasePrice() << std::endl;
	 }*/
	//int differences[] = { 1, 1, 0, 0, 0, -1, 1, -2, 1 };
	SDL_Event event;
	state_t nextState = MARKET;
	const char* names[] = { "Water", "Furs", "Food", "Ore", "Games", "Firearms", "Medicine", "Machines", "Narcotics" } ;
	
	setUpButtons(names, player->retInvArray());
	setButtonColors(differences);
	/*for(int i =0;i<10;i++)
	 buttons[i]->setColor(differences[i]);*/
	
	//setUpButtons(names, quantities, differences);
	
	//Load additional images
	SDL_Surface *descripBox = load_image("ShopDescrip.png",false);
	SDL_Surface *creditsBox = load_image("ShopCredits.png",false);
	SDL_Surface *qtyBox = load_image("ShopQTY.png",false);
	SDL_Surface *dispBox = load_image("ShopDisp.png",false);
	
	//Check proper loading
	if(descripBox == NULL || creditsBox == NULL || 
	   qtyBox == NULL || dispBox == NULL) 
	{
		std::cerr << "Error Loading additional MarketPlace resources" << std::endl;
	}
	//std::cout << "0: " <<prices[7] << std::endl;
	
	//Storage vars
	int quant = 1;
	//Load Font font surfaces
	TTF_Font *Font = TTF_OpenFont( "Futura.ttc", 20 );
	SDL_Color textColor = {255,255,255};
	
	buttons[0]->setState(buttons[0]->getState()+1);
	buttons[0]->setLastClicked(true);
    
	while (nextState == MARKET) {
        
        while(SDL_PollEvent(&event)) {
            if (event.type==SDL_QUIT) nextState = QUIT;
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_UP) quant++;
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_DOWN && quant>1) quant--;
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_LEFT) quant/=10;
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RIGHT) quant*=10;
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_b) {
				if(quant <=shopQuantities[lastPicked] && (player->getInventory(lastPicked)+quant)<=30)
					if(player->buy(lastPicked, prices[lastPicked], quant)) 
						shopQuantities[lastPicked]-=quant;
			}
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_s) 
				if(player->sell(lastPicked, prices[lastPicked], quant))
					shopQuantities[lastPicked]+=quant;
			
			//std::cout << "1: " <<prices[7] << std::endl;
			
			if(quant > 5000 || quant==0) quant = (quant+1)%5000;
            if (backButton.handle_input(event) == CLICKED) {
            	if (isTrader) nextState = TRAVEL;
            	else nextState = PLANET;
            }
			setUpButtons(names, player->retInvArray());
			
            for (unsigned int i = 0; i < buttons.size(); i++){
				if (buttons[i]->handle_input(event) == SHOP_CLICKED) {
                    if (i != lastPicked){
                        buttons[lastPicked]->setLastClicked(false);
                        buttons[lastPicked]->handle_input(event);
                        lastPicked = i;
                        buttons[i]->setLastClicked(true);
                    }
				}
            }
            
            if (buyButton.handle_input(event) == CLICKED){
                if(quant <=shopQuantities[lastPicked] && (player->getInventory(lastPicked)+quant)<=30){
                    if(player->buy(lastPicked, prices[lastPicked], quant)){
                        shopQuantities[lastPicked]-=quant;
                    }
                }
            }
            
            if (sellButton.handle_input(event) == CLICKED){
                if(player->sell(lastPicked, prices[lastPicked], quant)){
					shopQuantities[lastPicked]+=quant;
                }
            }
        }
		//std::cout << "2: " <<prices[7] << std::endl;
		
        SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));
        backButton.show(screen);
        
        //if (buttons[lastPicked]->getState() % 2 == 0)
        //    buttons[lastPicked]->setState(buttons[lastPicked]->getState()+1);
        
		for (int i = 0; i < 9; i++) {
			buttons[i]->setCoords(xOffset - (4 - i)*(4 - i)*6, yOffset + i*dY);
			buttons[i]->show(screen);
		}
		
        
		std::ostringstream title, description, credits, qty;
		//std::cout << "3: " <<prices[7] << std::endl;
		/*for (int i=0; i < itemList.size(); i++) {
		 std::cout << itemList[i] << std::endl;
		 std::cout << prices[i] << std::endl;
		 }*/
		//const char *curr_image= "medPack.png";
		std::stringstream out;
		out << names[lastPicked] << ".png";
		
		const char *curr_image= out.str().c_str();
		
		//std::cout << names[lastPicked] << std::endl;
		title << names[lastPicked];//curr.getName();
		description << "Price: " << prices[lastPicked] << "	Quantity: " << shopQuantities[lastPicked];// << " available)";//curr.getDescription();
		qty << quant;
		credits << "Credits: " << player->getCredits();
		
		//Current Display image
		SDL_Surface *dispSurf = load_image(curr_image,false);
		
		//Load font surfaces
		SDL_Surface *titleSurf = TTF_RenderText_Blended( Font, title.str().c_str(), textColor  );
		SDL_Surface *qtySurf = TTF_RenderText_Blended( Font, qty.str().c_str(), textColor  );
		SDL_Surface *creditsSurf = TTF_RenderText_Blended( Font, credits.str().c_str(), textColor  );
		SDL_Surface *descriptionSurf = TTF_RenderText_Blended( Font, description.str().c_str(), textColor  );
		
		//Apply additonal resource images
		apply_surface(360, 300, descripBox, screen);
		apply_surface(370, 305, titleSurf, screen);
		//apply_surface(415, 350, descriptionSurf, screen);
		
		
		apply_surface(355, 210, qtyBox, screen);
		apply_surface(355+qtyBox->w/2-qtySurf->w/2, 240, qtySurf, screen);
		
		apply_surface(360, 0, creditsBox, screen);
		apply_surface(360+10, 5, creditsSurf, screen);
		
		apply_surface(415, 50, dispBox, screen);
		apply_surface(415+dispBox->w/2-dispSurf->w/2, 50+dispBox->h/2-dispSurf->h/2, dispSurf, screen);
        apply_surface(375, 345, descriptionSurf, screen);
        
        buyButton.show(screen);
        sellButton.show(screen);
		
		SDL_FreeSurface(titleSurf);
		SDL_FreeSurface(qtySurf);
		SDL_FreeSurface(creditsSurf);
		SDL_FreeSurface(descriptionSurf);
		SDL_FreeSurface(dispSurf);
		
		
        //Update the screen
		if ( SDL_Flip( screen ) == -1 ) {
			std::cerr << "Error Updating screen." << std::endl;
		}
    }
	
	//resetting the buttons so they don't break when control comes back to this scene
    buttons[lastPicked]->setLastClicked(false);
	buttons[lastPicked]->handle_input(event);
	lastPicked = 0;
	
    return nextState;
}

/*
 * sets the info for the button text including the
 * item name, player quantity, and whether or not it
 * is a good idea to sell that item
 */
void MarketScene::setUpButtons(const char** names, int qties[])
{
	for (unsigned int i = 0; i < buttons.size(); i++){
		buttons[i]->setInfo(names[i], qties[i]);
	}
}

void MarketScene::setButtonColors(int *differences){
	for (unsigned int i = 0; i < buttons.size(); i++){
		buttons[i]->setColor(differences[i]);
	}
}
